package com.example.controller;

import com.example.entity.Userinfo;
import com.example.service.UserinfoService;
import com.example.util.CryptographyUtil;
import com.example.util.LogoutThread;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.crypto.hash.SimpleHash;
import org.apache.shiro.subject.Subject;
import org.apache.shiro.util.ByteSource;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Timer;
import java.util.TimerTask;



@RestController
public class LoginController
{
    @Autowired
    UserinfoService userinfoService;


    //登录的接口，接收前端userinfo，账号不存在返回"-1"，密码错误返回"0",当前时间与上次在线时间间隔小于5min返回"2"，登陆成功返回"1"，修改在线状态为在线并且更改上次在线时间为当前时间
//    @CrossOrigin(origins = "*",maxAge = 3600)//解决跨域问题
    @RequestMapping(value = "/login" )
    public String login(@RequestBody Userinfo userinfo,HttpServletResponse response,HttpServletRequest request) throws ParseException
    {
        String code = request.getParameter("code").toLowerCase();//转小写
        HttpSession session = request.getSession();
//        System.out.println(code);
        String verifyCode = null;
        try
        {
            verifyCode = session.getAttribute("verifyCode").toString().toLowerCase();//转小写
        }
        catch (NullPointerException e)
        {
            System.out.println("验证码过期,需要刷新验证码");
            return "-3";
        }

//        System.out.println(verifyCode);
        if (!code.equals(verifyCode))
        {
            return "-2";//验证码错误
        }
        UsernamePasswordToken token = new UsernamePasswordToken(userinfo.getName(), CryptographyUtil.decodeBase64(userinfo.getPassword()));
        Subject subject = SecurityUtils.getSubject();
        try
        {
            subject.login(token);

            DateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            String nowTime = df.format(new Date());
            String lastTime = userinfoService.select(userinfo.getName()).getLast_time();
            Date now = df.parse(nowTime);
            Date last = df.parse(lastTime);
            long diff = (now.getTime() - last.getTime()) / 1000;//当前时间与上次在线时间之差 -秒
            if (diff < 5 * 60 && userinfoService.select(userinfo.getName()).getIf_online() == 1)
            {
                System.out.println(userinfo.getName()+":当前在线");
                return "2";//在线
            }
            Cookie name = new Cookie("name",userinfoService.select(userinfo.getName()).getName());
//            Cookie password = new Cookie("password",userinfo.getPassword());
            Cookie if_online = new Cookie("if_online",userinfoService.select(userinfo.getName()).getIf_online().toString());
            Cookie last_time = new Cookie("last_time",userinfoService.select(userinfo.getName()).getLast_time().replace(" ",""));
            name.setMaxAge(60*60);
            if_online.setMaxAge(60*60);
            last_time.setMaxAge(60*60);
            name.setPath("/");
            if_online.setPath("/");
            last_time.setPath("/");
            response.addCookie(name);
            response.addCookie(if_online);
            response.addCookie(last_time);
            userinfoService.dateUpdate(userinfo,response);
            userinfo.setIf_online(1);
            userinfoService.onlineUpdate(userinfo,response);
            System.out.println(userinfo.getName()+":登陆成功");
//            userinfoService.logout(userinfo);
//            Thread logoutThread = new LogoutThread(userinfo,userinfoService);
//            logoutThread.start();
            return "1";

        }catch (UnknownAccountException e)
        {
            System.out.println("用户名错误");
            return "-1";
        }
        catch (IncorrectCredentialsException e)
        {
            System.out.println("密码错误");
            return "0";
        }

    }

    //如果前端有注册，接收前端userinfo，向数据库插入userinfo
    @RequestMapping(value = "/insert")
    public boolean insert(@RequestBody Userinfo userinfo)
    {
        ByteSource salt = ByteSource.Util.bytes(userinfo.getName());
        String newPassword = new SimpleHash("MD5",userinfo.getPassword(),salt,1024).toHex();
        userinfo.setPassword(newPassword);
        return userinfoService.userinfoInsert(userinfo);
    }
    //前端请求本接口，接收前端userinfo，更新上次在线时间并且设置在线状态为在线
    @RequestMapping(value = "/update")
    public boolean update(@RequestBody Userinfo userinfo,HttpServletResponse response,HttpServletRequest request)
    {
        HttpSession session = request.getSession();
        System.out.println("update");
        if (session!=null)
        {
            userinfoService.dateUpdate(userinfo,response);
            userinfo.setIf_online(1);
            userinfoService.onlineUpdate(userinfo,response);
            userinfoService.logout(userinfo);
        }
        return true;
    }

    @RequestMapping(value = "/logout")
    public boolean logout(@RequestBody Userinfo userinfo, HttpServletRequest request,HttpServletResponse response)
    {
        userinfoService.dateUpdate(userinfo,response);
        userinfo.setIf_online(0);
        userinfoService.onlineUpdate(userinfo,response);
//        HttpSession session = request.getSession();
//        session.invalidate();
        Subject currentUser = SecurityUtils.getSubject();
        currentUser.logout();
        System.out.println(userinfo.getName()+":登出成功");
        return true;
    }
}
